/**
 * Copyright (c) 2015 coderyuan.com. All Rights Reserved.
 * <p>
 * WlanApp
 * <p>
 * JdbcConnPool.java created on 下午6:41
 *
 * @author yuanguozheng
 * @version 1.0.0
 * @since 15/7/28
 */
package com.coderyuan.web.api.kit.database;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;

/**
 * JdbcConnPool
 *
 * @author yuanguozheng
 */
public class JdbcConnPool {

    private static JdbcConnPool sDb;

    private ComboPooledDataSource mDatasource;

    private JdbcConnPool() {
        try {
            mDatasource = new ComboPooledDataSource();
            mDatasource.setDriverClass(Configure.driver);
            mDatasource.setJdbcUrl(Configure.url);
            mDatasource.setUser(Configure.username);
            mDatasource.setPassword(Configure.password);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    public static JdbcConnPool getInstance() {
        if (sDb == null) {
            sDb = new JdbcConnPool();
        }
        return sDb;
    }

    public Connection getConn() {
        try {
            return mDatasource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void finalize() throws Throwable {
        DataSources.destroy(mDatasource);
        super.finalize();
    }

    public static class Configure {

        private static String driver;
        private static String url;
        private static String username;
        private static String password;

        public void init() {
            sDb = new JdbcConnPool();
        }

        public String getDriver() {
            return driver;
        }

        public void setDriver(String driver) {
            this.driver = driver;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}